package lads.flad.utils {
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.FileListEvent;
	import flash.filesystem.File;
	
	/**
	 * ...
	 * @author Dale J Williams
	 */
	public class FileList extends EventDispatcher {
		
		private var _path	:String;
		private var _list	:Vector.<String>;
		private var levels	:int;
		private var dir		:File;
		
		public function FileList(path:String=null) {
			_path = path || "";
			_list = new Vector.<String>();
		}
		
		public function load(path:String=null):void {
			if (!path) path = _path;
			
			levels = 1;
			dir = new File(File.applicationDirectory.url + path);
			dir.addEventListener(FileListEvent.DIRECTORY_LISTING, listDirectory);
			dir.getDirectoryListingAsync();
		}
		
		private function listDirectory(e:FileListEvent):void {
			levels--;
			for each(var file:File in e.files) {
				if (!file.isDirectory) {
					list.push(file.url.substr(file.url.indexOf(path)));
				} else {
					file.addEventListener(FileListEvent.DIRECTORY_LISTING, listDirectory);
					file.getDirectoryListingAsync();
					levels++;
				}
			}
			if (levels <= 0) {
				dispatchEvent(new Event(Event.COMPLETE));
			}
		}
		
		override public function toString():String {
			var str:String = "FileList: {\n";
			var i:int = -1;
			while (++i < list.length) {
				str += "\t" + list[i] + "\n";
			}
			return str + "}";
		}
		
		public function get path():String { return _path; }
		
		public function get list():Vector.<String> { return _list; }
		
	}

}